<template>
  <div class="login-container">
    <el-form
      ref="loginForm"
      :model="loginForm"
      :rules="rulesList"
      class="login-form"
      auto-complete="on"
      label-position="left"
      :validate-on-rule-change="false"
    >
      <div class="title-container">
        <h3 class="title">{{ $t('login.loginSystem') }}</h3>
        <lang-select class="set-language" />
      </div>
      <!-- 账号密码登录 -->
      <el-form-item
        v-show="model === 'passwordLogin'"
        prop="username"
        class="password-login"
      >
        <span class="svg-container">
          <svg-icon icon-class="user" />
        </span>
        <el-input
          ref="username"
          v-model="loginForm.username"
          :placeholder="$t('login.accountAlert')"
          name="username"
          type="text"
          tabindex="1"
          auto-complete="on"
        />
      </el-form-item>
      <el-form-item
        v-show="model === 'passwordLogin'"
        prop="password"
        class="password-login"
      >
        <span class="svg-container">
          <svg-icon icon-class="password" />
        </span>
        <el-input
          :key="passwordType"
          ref="password"
          v-model="loginForm.password"
          :type="passwordType"
          :placeholder="$t('login.pwd')"
          name="password"
          tabindex="2"
          auto-complete="on"
          @keyup.enter.native="handleLogin"
        />
        <span class="show-pwd" @click="showPwd">
          <svg-icon
            :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'"
          />
        </span>
      </el-form-item>
      <!-- 验证码登录 -->
      <el-form-item
        v-show="model !== 'passwordLogin'"
        prop="phoneNumber"
        class="item-from"
      >
        <el-input
          v-model="loginForm.phoneNumber"
          type="text"
          autocomplete="off"
          :placeholder="$t('login.inputPhone')"
        />
      </el-form-item>
      <el-form-item
        v-show="model !== 'passwordLogin'"
        prop="vertificationCode"
        class="item-from vertification"
      >
        <el-input
          v-model="loginForm.vertificationCode"
          div
          minlength="6"
          maxlength="6"
          :placeholder="$t('login.inputCode')"
        />
        <button
          class="getCode"
          type="button"
          :disabled="codeButtonStatus.status"
          @click="getSms()"
        >
          {{ codeButtonStatus.text }}
        </button>
      </el-form-item>
      <el-button
        :loading="loading"
        type="primary"
        style="width:100%;margin-bottom:30px;"
        @click.native.prevent="handleLogin"
      >{{ $t('login.login') }}</el-button>
      <div v-show="model === 'passwordLogin'" class="tips">
        <span
          style="margin-right:20px;"
        >{{ $t('login.userName') }}: admin</span>
        <span> {{ $t('login.password') }}: 123456</span>
      </div>
      <div class="menu">
        <div class="verification-code" @click="goVerification">
          <span style="color:#409EFF;">
            {{
              model === 'passwordLogin'
                ? $t('login.codeLogin')
                : $t('login.pwdLogin')
            }}
          </span>
        </div>
        <div class="register" @click="goRegister">
          <span style="color:#409EFF;"> {{ $t('login.goRegister') }} > </span>
        </div>
      </div>
    </el-form>
  </div>
</template>

<script>
import LangSelect from '@/components/LangSelect';
import { dataToBase64 } from '@/utils/';
import { validatePhone, validateVCode } from '@/utils/validate';
import code from '@/api/code';

export default {
  name: 'Login',
  components: { LangSelect },
  data() {
    const validateUsername = (rule, value, callback) => {
      if (value === '') {
        callback(new Error(this.$t('login.inputAccountAlert')));
      } else {
        callback();
      }
    };
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error(this.$t('login.passwordDigits')));
      } else {
        callback();
      }
    };
    const validatePhoneNumber = (rule, value, callback) => {
      if (value === '') {
        callback(new Error(this.$t('login.inputPhone')));
      } else if (validatePhone(value)) {
        callback(new Error(this.$t('login.phoneError')));
      } else {
        callback(); // true
      }
    };
    const validateCode = (rule, value, callback) => {
      if (value === '') {
        return callback(new Error(this.$t('login.inputCode')));
      } else if (validateVCode(value)) {
        return callback(new Error(this.$t('login.codeError')));
      } else {
        callback();
      }
    };
    return {
      loginForm: {
        username: '',
        password: '',
        phoneNumber: '',
        vertificationCode: '',
        rememberMe: true,
      },
      model: 'passwordLogin',
      pwdRules: {
        username: [
          { trigger: 'blur', validator: validateUsername, required: true },
        ],
        password: [
          { trigger: 'blur', validator: validatePassword, required: true },
        ],
      },
      codRules: {
        phoneNumber: [
          { validator: validatePhoneNumber, trigger: 'blur', required: true },
        ],
        vertificationCode: [
          { validator: validateCode, trigger: 'blur', required: true },
        ],
      },
      loading: false,
      passwordType: 'password',
      redirect: undefined,
      codeButtonStatus: {
        status: false,
        text: this.$t('login.getCode'),
      },
      bid: '',
      code: '',
    };
  },
  computed: {
    rulesList() {
      if (this.model === 'passwordLogin') {
        return this.pwdRules;
      } else {
        return this.codRules;
      }
    },
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true,
    },
  },
  created() {
    document.onkeyup = e => {
      if (this.$route.path == '/login' && e.code === 'Enter' || e.code === 'enter' || e.code === 'NumpadEnter') {
        this.handleLogin();
      }
    };
  },
  methods: {
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = '';
      } else {
        this.passwordType = 'password';
      }
      this.$nextTick(() => {
        this.$refs.password.focus();
      });
    },
    handleLogin() {
      this.$refs.loginForm.validate(async valid => {
        if (valid) {
          const params = Object.assign({}, this.loginForm);
          let loginInfo = {};
          params.password = dataToBase64(params.password);
          let actionUrl = 'user/login';
          if (this.model === 'vertificationLogin') {
            loginInfo = {
              phone: params.phoneNumber,
              code: params.vertificationCode,
              bid: this.bid,
              rememberMe: false,
            };
            if (!this.bid) {
              this.$message.error(this.$t('login.errCode'));
              return false;
            }
            await this.checkCode({
              phone: this.loginForm.phoneNumber,
              code: this.loginForm.vertificationCode,
              bid: this.bid,
            }).then(res => {
              if (res === '0') {
                this.loading = true;
                actionUrl = 'user/loginByCode';
              } else {
                this.loading = false;
                return false;
              }
            });
          } else {
            loginInfo = {
              username: params.username,
              password: params.password,
              rememberMe: params.rememberMe,
            };
          }
          this.$store
            .dispatch(actionUrl, loginInfo)
            .then(() => {
              this.$router.push({ path: this.redirect || '/home' });
              this.loading = false;
            })
            .catch(() => {
              this.loading = false;
            });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 切换到验证码登录
    goVerification() {
      this.$refs.loginForm.clearValidate();
      this.resetFromData();
      if (this.model === 'passwordLogin') {
        this.model = 'vertificationLogin';
      } else {
        this.model = 'passwordLogin';
      }
    },
    goRegister() {
      this.$router.push({ path: '/register' });
    },
    /**
     * 获取验证码
     */
    getSms() {
      // 验证手机号格式
      this.$refs.loginForm.validateField('phoneNumber', errText => {
        if (errText !== '') {
          this.$message.error(this.$t('login.inputCorrectPhone'));
          return false;
        }
        // 验证手机号是否注册过
        this.exist({ username: this.loginForm.phoneNumber }).then(res => {
          if (res) {
            // 发送验证码
            this.sendCode(this.loginForm.phoneNumber).then(res => {
              this.bid = res;
              // 获取验证码
              this.getCode(this.bid).then(res => {
                this.code = res;
                this.loginForm.vertificationCode = res;
                this.$refs.loginForm.clearValidate('vertificationCode');
              });
            });
            // 修改获取验证按钮状态
            this.updataButtonStatus({
              status: true,
              text: this.$t('login.sending'),
            });
            // 调定时器，倒计时
            this.countDown(60);
          } else {
            this.$message.error(this.$t('login.noUser'));
            return false;
          }
        });
      });
    },
    /**
     * 倒计时
     */
    countDown(number) {
      if (this.timer) {
        clearInterval(this.timer);
      }
      let time = number;
      this.timer = setInterval(() => {
        time--;
        if (time === 0) {
          clearInterval(this.timer);
          this.updataButtonStatus({
            status: false,
            text: this.$t('login.resend'),
          });
        } else {
          this.codeButtonStatus.text = `${time}${this.$t('login.second')}${this.$t('login.after')}${this.$t('login.resend')}`;
        }
      }, 1000);
    },
    /**
     * 清除表单数据
     */
    resetFromData() {
      this.$refs.loginForm.resetFields();
      this.clearCountDown();
    },
    /**
     * 清除倒计时
     */
    clearCountDown() {
      // 还原验证码按钮默认状态
      this.updataButtonStatus({
        status: false,
        text: this.$t('login.getCode'),
      });
      // 清除倒计时
      clearInterval(this.timer);
    },
    /**
     * 更新验证码按钮状态
     */
    updataButtonStatus(params) {
      this.codeButtonStatus.status = params.status;
      this.codeButtonStatus.text = params.text;
    },
    // 校验用户名是否存在
    async exist(phone) {
      const result = await code.exist(phone);
      return result.data.exist;
    },
    // 发送验证码
    async sendCode(phone) {
      const result = await code.sendCode(phone);
      return result.data.bid;
    },
    // 获取验证码
    async getCode(bid) {
      const result = await code.getCode(bid);
      return result.data.value;
    },
    // 验证码校验
    async checkCode(data) {
      const result = await code.checkCode(data);
      return result.data.code;
    },
  },
};
</script>

<style lang="scss">
/* 修复 input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

$bg: #283443;
$light_gray: #fff;
$cursor: #fff;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}

/* reset element-ui css */
.login-container {
  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;

    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      height: 47px;
      caret-color: $cursor;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }

  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    border-radius: 5px;
    color: #454545;
  }
}
</style>

<style lang="scss" scoped>
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;

.login-container {
  min-height: 100%;
  width: 100%;
  background-color: $bg;
  overflow: hidden;

  .login-form {
    position: relative;
    width: 520px;
    max-width: 100%;
    padding: 160px 35px 0;
    margin: 0 auto;
    overflow: hidden;
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    position: relative;

    .title {
      font-size: 26px;
      color: $light_gray;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }

    .set-language {
      color: #fff;
      position: absolute;
      top: 3px;
      font-size: 18px;
      right: 0px;
      cursor: pointer;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
  .menu {
    overflow: hidden;
    margin: 15px 0;
  }
  .register {
    float: right;
    color: #eee;
    span:hover {
      cursor: pointer;
      color: #999;
    }
  }
  .verification-code {
    color: #eee;
    float: left;
    span:hover {
      cursor: pointer;
      color: #999;
    }
  }
  .item-from {
    height: 54px;
    margin-bottom: 23px;
    /deep/ .el-form-item__error {
      padding-top: 12px;
    }
  }
  .block {
    display: block;
    width: 100%;
    height: 54px;
    margin-left: 13px;
  }
}
.getCode {
  position: absolute;
  height: 47px;
  line-height: 47px;
  top: 0;
  bottom: 0;
  right: 10px;
  background-color: #2d3a4b;
  color: #409eff;
  border-color: transparent;
  cursor: pointer;
  outline: none;
  &:disabled,
  &:disabled:hover {
    color: #999999;
    cursor: not-allowed;
  }
}
.getCode:hover {
  color: #fff;
}
</style>
